package com.cskaoyan.servlet;

import com.cskaoyan.service.AccountService;
import com.cskaoyan.service.AccountServiceImpl;
import com.cskaoyan.util.DruidUtils;
import com.cskaoyan.util.ProxyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author stone
 * @date 2022/03/16 11:41
 */
@WebServlet("/api/*")
public class AccountServlet extends HttpServlet {

    //AccountService accountService = new AccountServiceImpl();
    //AccountService accountService = ProxyUtil.getServiceProxy(AccountService.class);
    AccountService accountService = ProxyUtil.getServiceProxy(AccountServiceImpl.class);


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "text/html; charset=utf-8");
        String op = requestURI.replace(request.getContextPath() + "/api/", "");
        try {
            switch (op) {
                case "transfer":
                    transfer(request,response);
                    break;
                case "save":
                    save(request, response);
                    break;
                default:
                    response.getWriter().write("<h1>no match url</h1>");
            }
        } catch (SQLException throwables) {
            response.getWriter().write("<h1>应用程序正在维护</h1>");
            //throwables.printStackTrace();
        }
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        double money = Double.parseDouble(request.getParameter("money"));
        accountService.save(id, money);
    }

    private void transfer(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        int fromId = Integer.parseInt(request.getParameter("fromId"));
        int destId = Integer.parseInt(request.getParameter("destId"));
        double money = Double.parseDouble(request.getParameter("money"));
        accountService.transfer(fromId, destId, money);
        response.getWriter().write("转账成功");

    }
}
